package com.cn.dim.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;


public class SessionFilter implements Filter{
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
	}
	protected boolean isAjaxRequest(ServletRequest request) {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		String requestType = httpRequest.getHeader("X-Requested-With");
		if(requestType!=null && requestType.equals("XMLHttpRequest")) {
			return true;
		}
		return false;
	}
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse res = (HttpServletResponse)response; 
		String root = req.getContextPath();

		String returnUrl = req.getRequestURI();
		String[] notFilter = new String[] {"/login/login","/web/statics/login.html","/web/statics/index.html"};
		if(check(notFilter,returnUrl)){ 
			Object user=req.getSession().getAttribute("user");  
			if(user==null){  
				if(isAjaxRequest(request)){     //判断是否为ajax请求
					String requestType = req.getHeader("X-Requested-With");
					if (!StringUtils.isEmpty(requestType) && requestType.equalsIgnoreCase("XMLHttpRequest")) {  
						res.setHeader("sessionstatus", "timeout");  
						res.sendError(518, "session timeout.");  
					    return;  
					}  
				} else {
					res.sendRedirect(root+"/web/statics/login.html");  
				}
			}else{
				chain.doFilter(request, response);		
			}

		}else{
			chain.doFilter(request, response);
		}
	}
	public boolean check(String[] notFilter,String url){
		//url以css和js结尾的不进行拦截
		if(url.endsWith(".css") || url.endsWith(".js")|| url.endsWith(".ico")){
			return false;
		}
		//含有notFilter中的任何一个则不进行拦截
		for (String s : notFilter) {
			if (url.indexOf(s) != -1) {
				return false;
			}
		}
		return true;
	}
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
	}

}
